import moment from "moment";
declare const window: any;
import {message} from 'antd';
import axios from 'axios'

// 判断字符串是否包含中文
export function isChineseWord(str:string):boolean{
  let chineseReg = /[\u4E00-\u9FA5]+/g;
  return chineseReg.test(str);
}
// 判断字符串是否全部是中文
export function isAllChineseWord(str:string):boolean{
  let chineseReg = /^[\u4E00-\u9FA5]+$/;
  return chineseReg.test(str);
}
export function replaceHtmlTag(str:string,replaceStr:string):string{
  const htmlTags = ["<h1>","</h1>","<h2>","</h2>","<h3>","</h3>","<h4>","</h4>","<h5>","</h5>","<h6>","</h6>","<p>","</p>","<br>","<br/>",
  "<strong>","</strong>","<b>","</b>","<em>","</em>","<i>","</i>","<del>","</del>","<s>","</s>","<ins>","</ins>","<u>","</u>","<div>","</div>","<span>","</span>","<table>","</tabe>","<tr></tr>",
  "<td>","</td>","<th>","</th>","<thead>","</thead>","<tbody>","</tbody>","<ul>","</ul>","<ol>","</ol>","<li>","</li>","<dl>","</dl>","<dt>","</dt>","<dd>","</dd>","<form>","</form>"
  ]
  //替换常见html标签，也可以使用正则，但正则可能会误替换内容
  for(let i=0;i<htmlTags.length;i++){
    str = str.replaceAll(htmlTags[i],replaceStr ?? "")
    str = str.replaceAll(htmlTags[i],replaceStr.toUpperCase() ?? "")
  }
  return str
}

// CSS字符串转为对象
export function cssStringToObject (cssString: string) {
  const styleObject: Record<string, string> = {};
  
  if (!cssString || typeof cssString !== 'string') return styleObject;
  
  // 处理特殊字符和多个分号的情况
  const normalizedString = cssString
    .replace(/\/\*.*?\*\//g, '') // 移除CSS注释
    .replace(/\s+/g, ' ') // 合并多个空格
    .trim();
  
  const styleDeclarations = normalizedString.split(';');
  
  styleDeclarations.forEach(declaration => {
    const trimmed = declaration.trim();
    if (trimmed) {
      const colonIndex = trimmed.indexOf(':');
      if (colonIndex > 0) {
        let property = trimmed.substring(0, colonIndex).trim();
        let value = trimmed.substring(colonIndex + 1).trim();
        
        if (property && value) {
          // 特殊属性处理
          if (property === 'float') {
            property = 'cssFloat'; // React中float属性名为cssFloat
          }
          
          // 转换CSS属性名为React驼峰命名
          const reactProperty = property
            .replace(/^-ms-/, 'ms-') // 处理ms前缀
            .replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
          
          styleObject[reactProperty] = value;
        }
      }
    }
  });
  return styleObject;
};

export function bytesToMB(bytes: number): string {
  if (bytes === 0) return '0 MB';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
export function getRequestParams(u:string):any {
  let url = decodeURIComponent(u) // ?id="123456"&name="www";
  let object:any = {}
  if (url.indexOf('?') != -1) { // url中存在问号，也就说有参数。
    let str = url.substr(1) // 得到?后面的字符串
    let strs = str.split('&') // 将得到的参数分隔成数组[id="123456",name="www"];
    for (let i = 0; i < strs.length; i++) {
      object[strs[i].split('=')[0]] = strs[i].split('=')[1]// 得到{id:'123456',name:'www'}
    }
  }
  return object
}


export function getUrlParams(u:string):any {
  let url = decodeURIComponent(u) // ?redirect=/member/appraise?fromJump=1&aaa=1;
  let object:any = {}
  // 第一个?的索引
  let index = url.indexOf("?");
  if (index!= -1 && index+1 <= url.length-1) { // url中存在问号，也就说有参数。
    let str = url.substring(index+1) // 得到?后面的字符串
    console.log("sss",str)
    let strs = str.split('&') // 将得到的参数分隔成数组[redirect=/member/appraise?fromJump=1,aaa=1];
    for (let i = 0; i < strs.length; i++) {
      // 得到第一个=号的索引
      let firstEqualIndex = strs[i].indexOf('=')
      if(firstEqualIndex!=-1 && firstEqualIndex+1 <= strs[i].length-1){
        object[strs[i].slice(0,firstEqualIndex)] = strs[i].slice(firstEqualIndex+1)// 得到{"redirect": "/member/appraise?fromJump=1","aaa": "1"}
      }
    }
  }
  return object
}


// 根据文件链接获取文件拓展名
export function getExtByFileUrl(url:string){
  if(!url){
    return ''
  }
  let arr = url.split(".")
  if(arr.length>1){
    return arr[arr.length-1]
  }
  return ""
}

// 秒数转时分秒
export function secToHms(sec:number,split=':'){
  if(sec===0){
    return `00${split}00`
  }
  if(!sec){
    return sec;
  }
  if(sec<0){
    return sec;
  }
  let h = parseInt(`${sec / 3600}`);
  sec = sec % 3600;
  let m = parseInt(`${sec / 60}`);
  sec = sec % 60;
  let result = `${h>0?(h>=10?h:'0'+h):''}${h>0?split:''}${m>=10?m:'0'+m}${split}${sec>=10?sec:'0'+sec}`
  return result
}

export function downloadFileFn(url:string){
  if(!url){
    message.info("链接为空");
    return;
  }
  window.open(url);
}
/**
 * 异步文件下载
 * @getListApiParams {string} url 获取文件对应的URL
 * @getListApiParams {object} params 接口携带参数
 * @getListApiParams {string} fileName 文件名
 * @getListApiParams {string} fileType 文件类型
 */
export function downloadFile(url: string, params = {}, fileName: string, fileType: string, onProgress: (progress: number) => void) {
  params = Object.assign({}, params);

  axios({
    url,
    params,
    method: 'get',
    responseType: 'blob',
    onDownloadProgress: (progressEvent) => {
      if (progressEvent.total && onProgress) {
        const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        onProgress(progress); // 调用进度回调函数
      }
    }
  }).then(res => {
    const fileBlob = new Blob([res.data]); // 创建一个Blob对象
    const a = document.createElement('a');
    a.download = `${fileName}${fileType ? '.' + fileType : ''}`;
    a.href = URL.createObjectURL(fileBlob);
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    a.remove();
  });
}

export function getToken(): string {
  return window.localStorage.getItem("meedu-user-token") || "";
}

export function setToken(token: string) {
  window.localStorage.setItem("meedu-user-token", token);
}

export function clearToken() {
  window.localStorage.removeItem("meedu-user-token");
}

export function getPlayId(): string {
  return window.localStorage.getItem("meedu-play-id") || "";
}

export function savePlayId(id: string) {
  window.localStorage.setItem("meedu-play-id", id);
}

export function clearPlayId() {
  window.localStorage.removeItem("meedu-play-id");
}

export function getMsv(): string {
  return window.localStorage.getItem("meedu-msv") || "";
}

export function saveMsv(msv: string) {
  window.localStorage.setItem("meedu-msv", msv);
}

export function clearMsv() {
  window.localStorage.removeItem("meedu-msv");
}

export function saveLoginCode(code: string) {
  window.localStorage.setItem("login_code", code);
}

export function getLoginCode() {
  return window.localStorage.getItem("login_code");
}

export function clearLoginCode() {
  window.localStorage.removeItem("login_code");
}

export function saveSessionLoginCode(code: string) {
  if (!code) {
    return;
  }
  window.sessionStorage.setItem("login_code:" + code, code);
}

export function getSessionLoginCode(code: string) {
  return window.sessionStorage.getItem("login_code:" + code);
}

export function clearSessionLoginCode(code: string) {
  return window.sessionStorage.removeItem("login_code:" + code);
}

export function getCommentTime(dateStr: string) {
  if (dateStr === "刚刚") {
    return "刚刚";
  }
  const interval = moment().diff(moment(dateStr), "seconds");
  if (interval < 60) {
    return "刚刚";
  } else if (interval < 60 * 60) {
    let tempTime = Math.floor(interval / 60);
    return `${tempTime}分钟前`;
  } else if (interval < 60 * 60 * 24) {
    let tempTime = Math.floor(interval / (60 * 60));
    return `${tempTime}小时前`;
  } else if (interval < 60 * 60 * 24 * 7) {
    let tempTime = Math.floor(interval / (60 * 60 * 24));
    return `${tempTime}天前`;
  } else if (interval < 60 * 60 * 24 * 365) {
    return moment(dateStr).utcOffset(0).format("MM-DD");
  } else {
    return moment(dateStr).utcOffset(0).format("YYYY-MM-DD");
  }
}

export function changeTime(dateStr: string) {
  const interval = moment().diff(moment(dateStr), "seconds");
  if (interval < 60) {
    return "刚刚";
  } else if (interval < 60 * 60) {
    let tempTime = Math.floor(interval / 60);
    return `${tempTime}分钟前`;
  } else if (interval < 60 * 60 * 24) {
    let tempTime = Math.floor(interval / (60 * 60));
    return `${tempTime}小时前`;
  } else if (interval < 60 * 60 * 24 * 7) {
    let tempTime = Math.floor(interval / (60 * 60 * 24));
    return `${tempTime}天前`;
  // } else if (interval < 60 * 60 * 24 * 365) {
  //   return moment(dateStr).utcOffset(0).format("MM-DD HH:mm");
  // } else {
  //   return moment(dateStr).utcOffset(0).format("YYYY-MM-DD HH:mm");
  // }
  } else {
    // 直接比较年份
    return moment(dateStr).utcOffset(8).year() === moment().utcOffset(8).year()
      ? moment(dateStr).utcOffset(8).format("MM-DD HH:mm")
      : moment(dateStr).utcOffset(8).format("YYYY-MM-DD HH:mm");
  }
}

export function dateFormat(dateStr: string) {
  return moment(dateStr).format("YYYY-MM-DD HH:mm");
}
export function dateFormat1(dateStr: string) {
  return moment(dateStr).format("YYYY-MM-DD HH:mm:ss");
}

export function generateUUID(): string {
  let guid = "";
  for (let i = 1; i <= 32; i++) {
    let n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
    if (i === 8 || i === 12 || i === 16 || i === 20) guid += "-";
  }
  return guid;
}

export function transformBase64ToBlob(
  base64: string,
  mime: string,
  filename: string
): File {
  const arr = base64.split(",");
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

export function getHost() {
  return window.location.protocol + "//" + window.location.host + "/";
}

export function inStrArray(array: string[], value: string): boolean {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === value) {
      return true;
    }
  }
  return false;
}

export function getAppUrl() {
  let host = window.location.protocol + "//" + window.location.host;
  let pathname = window.location.pathname;
  if (pathname && pathname !== "/") {
    host += pathname;
  }
  return host;
}

export function random(minNum: number, maxNum: number) {
  switch (arguments.length) {
    case 1:
      return Math.random() * minNum + 1, 10;
    case 2:
      return Math.random() * (maxNum - minNum + 1) + minNum, 10;
    default:
      return 0;
  }
}

export function getShareHost() {
  let hash = window.location.hash;

  if (hash.match("#")) {
    hash = "/#/";
  } else {
    hash = "/";
  }

  let host = window.location.protocol + "//" + window.location.host + hash;
  return host;
}

export function isMobile() {
  let flag = navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  );
  return flag;
}

export function SPAUrlAppend(baseUrl: string, queryParams: any) {
  let parseBaseUrl = new URL(baseUrl);
  return (
    parseBaseUrl.protocol +
    "//" +
    parseBaseUrl.host +
    parseBaseUrl.pathname +
    "#/?" +
    (parseBaseUrl.search ? parseBaseUrl.search + "&" : "") +
    queryParams
  );
}

export function codeRender(el: any) {
  if (!el) {
    return;
  }
  let blocks = el.querySelectorAll("pre") || el.querySelectorAll("code");
  blocks.forEach((block: any) => {
    window.hljs.highlightBlock(block);
  });
  return el;
}

export function latexRender(el: any) {
  if (!el) {
    return;
  }
  var reg1 = new RegExp("&nbsp;", "g");
  var reg2 = new RegExp("&amp;", "g");
  var reg3 = new RegExp("nbsp;", "g");
  var reg4 = new RegExp("amp;", "g");
  el.innerHTML = el.innerHTML.replace(reg1, "");
  el.innerHTML = el.innerHTML.replace(reg2, "&");
  el.innerHTML = el.innerHTML.replace(reg3, "");
  el.innerHTML = el.innerHTML.replace(reg4, "");
  window.renderMathInElement(el, {
    delimiters: [
      { left: "$$", right: "$$", display: true },
      { left: "$", right: "$", display: false },
      { left: "\\(", right: "\\)", display: false },
      { left: "\\[", right: "\\]", display: true },
    ],
    macros: {
      "\\ge": "\\geqslant",
      "\\le": "\\leqslant",
      "\\geq": "\\geqslant",
      "\\leq": "\\leqslant",
    },
    options: {
      skipHtmlTags: ["noscript", "style", "textarea", "pre", "code"],
      // 跳过mathjax处理的元素的类名，任何元素指定一个类 tex2jax_ignore 将被跳过，多个累=类名'class1|class2'
      ignoreHtmlClass: "tex2jax_ignore",
    },
    svg: {
      fontCache: "global",
    },
    throwOnError: false,
  });

  return el;
}

export function getBindMobileKey(): string {
  return window.localStorage.getItem("meedu-bind-mobile") || "";
}

export function setBindMobileKey() {
  window.localStorage.setItem("meedu-bind-mobile", "ok");
}

export function clearBindMobileKey() {
  window.localStorage.removeItem("meedu-bind-mobile");
}

export function getFaceCheckKey(): string {
  return window.localStorage.getItem("meedu-face-check") || "";
}

export function setFaceCheckKey() {
  window.localStorage.setItem("meedu-face-check", "ok");
}

export function clearFaceCheckKey() {
  window.localStorage.removeItem("meedu-face-check");
}

